import { NextRequest } from "next/server";
import * as jose from "jose";

import admin_config from "@/config/admin_config";


const secret = new TextEncoder().encode(`secret-key-phrase`);
export const goesGet = async (jwtToken: string) => {
  try {
    const { payload: jwtData, protectedHeader } = await jose.jwtVerify(
      jwtToken,
      secret
    );
    return {
      jwtData,
      protectedHeader,
    };
  } catch (err) {
    console.log(err);
    return false;
  }
};

export const goesSet = async (
  data: any,
  expiresIn:string = admin_config.jose.expiresIn
) => {
  const jwtToken = await new jose.SignJWT(data)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(expiresIn)
    .sign(secret);
  return jwtToken;
};
export const isAuthenticated = async (request: NextRequest): Promise<any> => {
  const cookie = request.cookies.get(admin_config.token);
  if(!cookie){
    return false
  }
  const result = await goesGet(cookie?.value || "");

  if (result !== false) {
    return result;
  }
  return false;
};
